const _ = require('lodash');

module.exports = class extends think.Controller {
  async __before() {
    this.assign('siteName', 'Thincho');
    this.assign('pageTitle', this.getPageTitle());

    const newestPosts = await think.model('contents').where({ type: 'post' }).order('created DESC').limit(5).select();
    const allCategories = await think.model('metas').where({ type: 'category' }).order('`order` ASC').select();
    // 只显示两级
    const levelCategories = _.filter(allCategories, item => item.parent === 0);
    const subCategories = _.difference(allCategories, levelCategories);
    for (const category of levelCategories) {
      if (think.isEmpty(category.children)) {
        category.children = [];
      }
      for (const cate of subCategories) {
        if (category.mid === cate.parent) {
          category.children.push(cate);
        }
      }
    }
    this.assign('newestPosts', newestPosts);
    this.assign('categories', levelCategories);
  }

  getPageTitle() {
    let pageTitle = 'Thincho';
    switch (this.ctx.controller) {
      case 'index':
        pageTitle = 'Thincho';
        break;
      case 'posts':
        switch (this.ctx.action) {
          case 'list':
            pageTitle = '文章列表';
            break;
          case 'search':
            pageTitle = `包含关键字 %s 的文章`;
            break;
          case 'detail':
            pageTitle = '%';
            break;
          case 'category':
            pageTitle = '分类 %s 下的文章';
          case 'tags':
            pageTitle = '标签 %s 下的文章';
            break;
          case 'archives':
            pageTitle = '%';
            break;
        }
        break;
      case 'pages':
        switch (this.ctx.action) {
          case 'detail':
            pageTitle = '%';
            break;
        }
        break;
    }
    return pageTitle;
  }

  setPageTile(param, isReplace = false) {
    if (think.isEmpty(param)) {
      return;
    }

    if (isReplace) {
      this.assign('pageTitle', param);
      return;
    }

    // 替换 %s
    let pageTitle = this.assign('pageTitle');
    pageTitle = pageTitle.replace('%s', param);
    this.assign('pageTitle', pageTitle);
  }

  /**
   * 扩展 display，加入模板主题支持
   * @param {string} fileName 模板文件名
   */
  display(fileName = '') {
    // 模块名 + 主题名称（目录和名称必须一致）
    const themeName = 'default';
    const themePath = `${this.ctx.module}/${themeName}/`;
    if (think.isEmpty(fileName)) {
      // 控制器名 + 分隔符 + 动作名 + 文件后缀
      const viewType = think.config('view.type');
      const viewSep = think.config(`view.${viewType}.sep`);
      const viewExtname = think.config(`view.${viewType}.extname`);
      fileName = this.ctx.controller + viewSep + this.ctx.action + viewExtname;
    }
    return super.display(themePath + fileName);
  }
};
